#!/usr/bin/env python3
import json
import http.server
import socketserver
from urllib.parse import urlparse, parse_qs
from datetime import datetime
import threading
import time

PORT = 8081

class EmergencyAPIHandler(http.server.BaseHTTPRequestHandler):
    def do_OPTIONS(self):
        """处理CORS预检请求"""
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
        self.end_headers()
    
    def do_GET(self):
        """处理GET请求"""
        parsed_path = urlparse(self.path)
        path = parsed_path.path
        
        # 设置CORS头
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Content-Type', 'application/json')
        
        if path == '/health':
            self.send_response(200)
            self.end_headers()
            response = {
                'status': 'OK',
                'message': '紧急Python服务器运行中',
                'timestamp': datetime.now().isoformat(),
                'server': 'Emergency Python Server'
            }
            self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8'))
            
        elif path == '/api/menu':
            self.send_response(200)
            self.end_headers()
            response = {
                'success': True,
                'data': [
                    {'id': 1, 'name': '汉堡', 'price': 25.00, 'category': '主食', 'available': True},
                    {'id': 2, 'name': '薯条', 'price': 12.00, 'category': '小食', 'available': True},
                    {'id': 3, 'name': '可乐', 'price': 8.00, 'category': '饮料', 'available': True},
                    {'id': 4, 'name': '鸡翅', 'price': 18.00, 'category': '主食', 'available': True}
                ]
            }
            self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8'))
            
        elif path == '/api/orders':
            self.send_response(200)
            self.end_headers()
            response = {
                'success': True,
                'data': [
                    {
                        'id': 'ORDER-1234567890',
                        'items': [{'name': '汉堡', 'quantity': 2, 'price': 25.00}],
                        'total': 50.00,
                        'status': 'completed',
                        'createdAt': datetime.now().isoformat()
                    }
                ]
            }
            self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8'))
            
        elif path == '/api/coupons':
            self.send_response(200)
            self.end_headers()
            response = {
                'success': True,
                'data': [
                    {
                        'id': 1,
                        'title': '新用户优惠',
                        'discount': 10,
                        'type': 'percentage',
                        'validUntil': '2024-12-31',
                        'active': True
                    },
                    {
                        'id': 2,
                        'title': '满50减10',
                        'discount': 10,
                        'type': 'fixed',
                        'minAmount': 50,
                        'validUntil': '2024-12-31',
                        'active': True
                    }
                ]
            }
            self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8'))
            
        elif path == '/api/users/profile':
            self.send_response(200)
            self.end_headers()
            response = {
                'success': True,
                'data': {
                    'id': 1,
                    'username': 'admin',
                    'email': 'admin@example.com',
                    'points': 100,
                    'level': 'VIP',
                    'joinDate': '2024-01-01'
                }
            }
            self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8'))
            
        else:
            self.send_response(404)
            self.end_headers()
            response = {'success': False, 'message': 'API接口不存在'}
            self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8'))
    
    def do_POST(self):
        """处理POST请求"""
        parsed_path = urlparse(self.path)
        path = parsed_path.path
        
        # 读取请求体
        content_length = int(self.headers.get('Content-Length', 0))
        post_data = self.rfile.read(content_length)
        
        try:
            request_data = json.loads(post_data.decode('utf-8')) if post_data else {}
        except:
            request_data = {}
        
        # 设置CORS头
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Content-Type', 'application/json')
        
        if path == '/api/auth/login':
            username = request_data.get('username', '')
            password = request_data.get('password', '')
            
            if username == 'admin' and password == 'admin123':
                self.send_response(200)
                self.end_headers()
                response = {
                    'success': True,
                    'token': f'emergency-token-{int(time.time())}',
                    'user': {'id': 1, 'username': 'admin', 'role': 'admin'}
                }
            else:
                self.send_response(401)
                self.end_headers()
                response = {'success': False, 'message': '用户名或密码错误'}
            
            self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8'))
            
        elif path == '/api/orders':
            self.send_response(200)
            self.end_headers()
            response = {
                'success': True,
                'orderId': f'ORDER-{int(time.time())}',
                'message': '订单创建成功',
                'data': request_data
            }
            self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8'))
            
        else:
            self.send_response(404)
            self.end_headers()
            response = {'success': False, 'message': 'API接口不存在'}
            self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8'))
    
    def log_message(self, format, *args):
        """自定义日志格式"""
        print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {format % args}")

def start_server():
    """启动服务器"""
    with socketserver.TCPServer(("", PORT), EmergencyAPIHandler) as httpd:
        print(f"🚀 紧急Python服务器启动成功!")
        print(f"📍 服务地址: http://localhost:{PORT}")
        print(f"🏥 健康检查: http://localhost:{PORT}/health")
        print(f"📚 API接口:")
        print(f"   - GET  /api/menu (菜单数据)")
        print(f"   - POST /api/auth/login (用户登录)")
        print(f"   - GET  /api/orders (订单列表)")
        print(f"   - POST /api/orders (创建订单)")
        print(f"   - GET  /api/coupons (优惠券)")
        print(f"   - GET  /api/users/profile (用户信息)")
        print(f"⚡ 状态: 紧急模式 - 临时解决方案")
        print(f"🔑 测试账号: admin / admin123")
        print("\n按 Ctrl+C 停止服务器")
        
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\n🛑 服务器已停止")
            httpd.shutdown()

if __name__ == "__main__":
    start_server()